package ua.vn.ticket_scanner.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.UnsupportedEncodingException;

import ua.vn.ticket_scanner.R;
import ua.vn.ticket_scanner.network.data.ConnectResult;
import ua.vn.ticket_scanner.network.data.JSONKeys;
import ua.vn.ticket_scanner.network.task.http.LoginTask;
import ua.vn.ticket_scanner.network.utils.ResultRunnable;
import ua.vn.ticket_scanner.user.UserData;
import ua.vn.ticket_scanner.utils.TPreferenceManager;
import ua.vn.ticket_scanner.utils.VibratorHelper;

/**
 * Created by Ivan on 21.06.13.
 */
public class LoginActivity extends Activity {

    private static final int POST_DELAY = 2000;

    private ImageView mLogoView;
    private EditText mLoginText;
    private EditText mPasswordText;
    private Button mButton;
    private ProgressBar mProgressBar;
    private final ResultRunnable mResultRunnable = new ResultRunnable() {
        @Override
        public void run() {
            final LoginActivity activity = LoginActivity.this;
            UserData.getInstance().setToken(null);

            if(activity != null) {
                lock(false);
            }

            if(mConnectResult == null) {
                if(activity == null)
                    return;
                animShowError(getResources().getString(R.string.message_connect_failed));
                return;
            }

            String error = mConnectResult.get(JSONKeys.ERROR_CODE);
            if (error == null) {

                // get data from JSON
                String id = mConnectResult.get(JSONKeys.CONTROLLER_ID);
                String secretKey = mConnectResult.get(JSONKeys.SECRET_KEY);
                String firstName = mConnectResult.get(JSONKeys.CONTROLLER_FIRST_NAME);
                String secondName = mConnectResult.get(JSONKeys.CONTROLLER_SECOND_NAME);

                try {
                    firstName = new String(firstName.getBytes("UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                // set data about controller
                UserData.getInstance().setId(id);
                UserData.getInstance().setToken(secretKey);
                UserData.getInstance().setFirstName(firstName);
                UserData.getInstance().setSecondName(secondName);

                // save controller data in the preference
                TPreferenceManager.getInstance().saveUserData();

                // if activity has died, other login need to ignoring
                if(activity == null)
                    return;

                String message = getResources().getString(R.string.message_welcome);
                animShowSuccess(message + " " + UserData.getInstance().getFirstName() + "!");
                mProgressBar.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        startActivity(new Intent(activity, MainActivity.class));
                    }
                }, POST_DELAY);
            } else {

                // if activity has died, other login need to ignoring
                if(activity == null)
                    return;

                animShowError(ConnectResult.errorCodes.get(error));
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);

        mLogoView = (ImageView) findViewById(R.id.imageLogo);
        mLoginText = (EditText) findViewById(R.id.loginText);
        mPasswordText = (EditText) findViewById(R.id.passwordText);
        mButton = (Button) findViewById(R.id.btn_login);
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);

        mProgressBar.setIndeterminate(true);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                lock(true);
                String loginName = mLoginText.getText().toString();
                String loginPassword = mPasswordText.getText().toString();
                UserData.getInstance().clear();
                LoginTask login = new LoginTask(loginName, loginPassword);
                login.setOnPostExecute(mResultRunnable);
                login.execute();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mLogoView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.effect_logo_move));
    }

    @Override
    public void onBackPressed() {
        // super.onBackPressed();
        startActivity(new Intent(this, MainActivity.class));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLogoView = null;
        mLoginText = null;
        mPasswordText = null;
        mButton = null;
        mProgressBar = null;
    }

    private void lock(boolean isLock) {
        if(isLock) {
            mButton.setEnabled(false);
            mProgressBar.setVisibility(View.VISIBLE);
        } else {
            mButton.setEnabled(true);
            mProgressBar.setVisibility(View.INVISIBLE);
        }
    }

    private void animShowError(String message) {
        VibratorHelper.doubleShortVibro();
        final RelativeLayout layout = (RelativeLayout) findViewById(R.id.error);
        TextView text = (TextView) findViewById(R.id.errorText);
        text.setText(message);
        Animation anim = AnimationUtils.loadAnimation(this, R.anim.effect_show_throw);
        anim.setAnimationListener(
                new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                        layout.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        layout.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
        layout.startAnimation(anim);
    }

    private void animShowSuccess(String message) {
        VibratorHelper.shortVibro();
        final RelativeLayout layout = (RelativeLayout) findViewById(R.id.success);
        TextView text = (TextView) findViewById(R.id.successText);
        text.setText(message);
        Animation anim = AnimationUtils.loadAnimation(this, R.anim.effect_show_throw);
        anim.setAnimationListener(
                new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                        layout.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        layout.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
        layout.startAnimation(anim);
    }
}